package peopledetectservice

import (
	"bytes"
	"encoding/json"
	"gcc/global"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)


func Start(pd *gin.Engine)error{
	pd.GET("/heart", HeartBeatService)
	pd.POST("/service", new(ServiceDependencyMapping).UpdateService)
	pd.POST("/predict", PDService)
	pd.GET("/", func(context *gin.Context) {
		context.JSON(http.StatusOK,gin.H{
			"data":"ok",
		})
	})
	//fmt.Println("aaaaaaa")
	// 将struct转化成json,并且实现了io.reader这个接口（先上json包里看有没有现成的，如果有就用，没有就自己写）
	buff := new(bytes.Buffer)
	enc := json.NewEncoder(buff)
	err := enc.Encode(Reg)
	if err != nil {
		return err
	}
	// 发送http.post请求给注册服务, 给三次机会，一旦三次都失败的话，就会返回错误，停止启动服务。
	attemp := 0
	rePost:
	_, err = http.Post("http://"+string(global.RegistryAddress)+"/service", "application/json", buff)
	if err != nil {
		log.Printf("detect service to registry failed %d \n", attemp)
		attemp++
		if attemp < 3 {
			goto rePost
		}else{
			return err
		}
	}
	log.Println("注册成功")
	return nil
}


func Shutdown(reg Registration) error {
	req, err := http.NewRequest(http.MethodDelete, string(global.RegistryAddress), bytes.NewBuffer([]byte(reg.ServiceURL)))
	if err != nil {
		return err
	}
	req.Header.Add("Content-Type", "text/plain")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	if resp.StatusCode == http.StatusOK {
		log.Println("shutdown service ok, already tell the registry center")
	}
	return nil
}

